import { useCallback, useEffect, useRef, useState } from 'react';
import styles from './index.module.less';

const FloatButton = () => {
  const [position, setPosition] = useState({
    top: '10px',
    right: '400px',
  });
  const [isDragging, setIsDragging] = useState(false);
  const [offset, setOffset] = useState({ x: 0, y: 0 });
  const [hasMoved, setHasMoved] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  const handleMouseDown = (e: React.MouseEvent) => {
    e.preventDefault();
    setHasMoved(false);
    if (containerRef.current) {
      const rect = containerRef.current.getBoundingClientRect();
      setOffset({
        x: e.clientX - rect.left,
        y: e.clientY - rect.top,
      });
      setIsDragging(true);
    }
  };

  const handleMouseMove = useCallback(
    (e: MouseEvent) => {
      if (!isDragging || !containerRef.current) return;

      // 获取窗口边界
      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;
      const containerWidth = containerRef.current.offsetWidth;
      const containerHeight = containerRef.current.offsetHeight;

      // 计算新位置，确保在窗口范围内
      let newLeft = e.clientX - offset.x;
      let newTop = e.clientY - offset.y;

      // 限制在窗口范围内
      newLeft = Math.max(0, Math.min(windowWidth - containerWidth, newLeft));
      newTop = Math.max(0, Math.min(windowHeight - containerHeight, newTop));

      // 转换为相对于右侧的位置
      setPosition({
        top: `${newTop}px`,
        right: `${windowWidth - newLeft - containerWidth}px`,
      });

      // 设置移动标记
      setHasMoved(true);
    },
    [isDragging, offset],
  );

  const handleMouseUp = useCallback(() => {
    setIsDragging(false);
  }, []);

  useEffect(() => {
    if (isDragging) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
      return () => {
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
      };
    }
  }, [isDragging, handleMouseMove, handleMouseUp]);

  return (
    <div
      ref={containerRef}
      className={`${styles.root} ${isDragging ? styles.dragging : ''}`}
      style={{
        top: position.top,
        right: position.right,
      }}
      onMouseDown={handleMouseDown}
    >
      <button
        type="button"
        onClick={() => {
          if (!hasMoved) {
            console.log('click');
          }
        }}
      >
        TEST
      </button>
    </div>
  );
};
export default FloatButton;
